package ay.job;

import ay.model.Mood;
import ay.model.UserMoodPraiseRel;
import ay.service.MoodService;
import ay.service.UserMoodPraiseRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Component
@Configurable
@EnableScheduling
public class PraiseDataSaveDBJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMoodPraiseRelService userMoodPraiseRelService;

    @Autowired
    private MoodService moodService;

    private static final String PRAISE_HASH_KEY = "springMVC-learning.mood.id.list.key";

    @Scheduled(cron = "*/10 * *  * * *")
    public void savePraiseDataToDB(){
        //1,获取所有在redis缓存中被点赞的说说的id
        Set<String> moods = redisTemplate.opsForSet().members(PRAISE_HASH_KEY);
        if (CollectionUtils.isEmpty(moods)){
            return;
        }
        for (String moodId : moods){
            if (redisTemplate.opsForSet().members(moodId) == null){
                //该说说没有被点赞
                continue;
            }
            else {
                //2,在redis缓存中，通过说说获取所有点赞用户的id列表
                Set<String> userIds = redisTemplate.opsForSet().members(moodId);
                if (CollectionUtils.isEmpty(userIds)){
                    return;
                }
                else {
                    //3,通过循环来保存moodId和userId的关联关系到MySQL数据库
                    for (String userId : userIds){
                        UserMoodPraiseRel userMoodPraiseRel = new UserMoodPraiseRel();
                        userMoodPraiseRel.setUserId(userId);
                        userMoodPraiseRel.setMoodId(moodId);
                        //保存说说与用户的关联关系
                        userMoodPraiseRelService.save(userMoodPraiseRel);
                    }
                    Mood mood = moodService.findById(moodId);
                    //4,更新说说的点赞数量
                    //说说总点赞量= redis点赞数量 + 数据库点赞数量
                    mood.setPraiseNum(mood.getPraiseNum() + redisTemplate.opsForSet().size(moodId).intValue());
                    moodService.update(mood);
                    //5，清除redis缓存中的数据
                    redisTemplate.delete(moodId);
                }
            }
        }
        //6，清除redis缓存中的数据
        redisTemplate.delete(PRAISE_HASH_KEY);
    }

}
